package com.ticket.common.utils;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Id2Utils {
    private static final Logger logger = LoggerFactory.getLogger(Id2Utils.class);
    public static final String url = "https://idenauthen.market.alicloudapi.com/idenAuthentication";
    public static final String appCode = "f7d79ead6d954811b3a4eee6acd02993";//"aa6c10e445f340e1a32f4880786d37a8";

    /**
     * 身份认证返回码 0000：身份信息匹配
     */
    public static final String RESPCODE_SUCCESS = "0000";


    /**
     * {
     *   "name": "张三",
     *   "idNo": "340421190710145412",
     *   "respMessage": "身份证信息匹配",
     *   "respCode": "0000",
     *   "province": "安徽省",
     *   "city": "淮南市",
     *   "county": "凤台县",
     *   "birthday": "19071014",
     *   "sex": "M",
     *   "age": "111"
     * }
     * @param name
     * @param idNo
     * @return
     * @throws IOException
     */
    public static JSONObject postData(String name, String idNo) throws IOException {
        String result = "";
        RequestBody formBody = new FormBody.Builder().add("name", name).add("idNo", idNo).build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(formBody).build();
        logger.info("postData url:{} idNo:{} name:{}",url,idNo,name);
        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            logger.error("execute failed, message:", e);
        }

        assert response != null;
        if (!response.isSuccessful()) {
            // 状态码为403时一般是套餐包用尽，需续购；注意：续购不会改变秘钥（appCode），仅增加次数
            // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
            logger.warn("request failed----" + "返回状态码" + response.code()  + ",message:" + response.message());
        }
        result = response.body().string();
        return JSONObject.parseObject(result);
    }
}
